package gmodel

import "gorm.io/gorm"

type IDbRedisHash interface {
	IDb
	IRedisHash
}

type BaseDbRedisHash struct {
	BaseDb
	BaseRedisHash
}

func (this *BaseDbRedisHash) DbRedisGet(child IDbRedisHash, syncRedis ...bool) error {
	var err error
	if err = this.RedisGet(child); err != nil {
		if err = this.DbGet(child, "id", child.GetId()); err != nil {
			return err
		}
	} else if len(syncRedis) == 0 || syncRedis[0] {
		_ = this.RedisSet(child)
	}
	return nil

}

func (this *BaseDbRedisHash) DbRedisSave(child IDbRedisHash, isAdd ...bool) (err error) {
	return child.Db().Transaction(func(tx *gorm.DB) error {
		if child.GetId() == 0 || (len(isAdd) > 0 && isAdd[0]) {
			if err = tx.Create(child).Error; err != nil { //新增到数据库
				return err
			}
		} else {
			if err = tx.Save(child).Error; err != nil {
				return err
			}
		}
		if err = this.RedisSet(child); err != nil {
			return err
		}
		//返回 nil 提交事务
		return nil
	})
}

func (this *BaseDbRedisHash) DbRedisDel(child IDbRedisHash) error {
	return child.Db().Transaction(func(tx *gorm.DB) error {
		if err := this.RedisDel(child); err != nil {
			return err
		} else if err = tx.Delete(child).Error; err != nil {
			return err
		}
		return nil
	})
}
